'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const { wallpaper_id, uniIdToken,uid } = event;
  
  try {
    // 验证壁纸ID
    if (!wallpaper_id || typeof wallpaper_id !== 'string') {
      return {
        code: 400,
        message: '壁纸ID无效'
      };
    }
    
    // 检查壁纸是否存在
    const wallpaper = await db.collection('wallpapers').doc(wallpaper_id).get();
    if (!wallpaper.data) {
      return {
        code: 404,
        message: '壁纸不存在'
      };
    }
    
    // 获取用户ID（可选）
    let userId = uid;
    // 如果用户已登录，记录到downloads集合
    await db.collection('downloads').add({
      user_id: userId,
      wallpaper_id: wallpaper_id,
      download_time: new Date()
    });
    if (uniIdToken) {
      try {
		const uniID = require('uni-id-common')
		console.log('MMMMMMM',{uniID});
        const uniIDIns = uniID.createInstance({ context });
        const userInfo = await uniIDIns.checkToken(uniIdToken);
        
        if (userInfo.code === 0) {
          userId = userInfo.uid||event.uid;
          console.log('用户已登录，用户ID:', userId);
          console.log('用户已登录，userInfo:', userInfo);
          // 先检查是否有downloadlist集合
          const collections = await db.collection('downloads').get();
          let hasFeaturedCollection = collections.data.some(col => col.name === 'downloadlist');
          
          // 如果没有downloadlist集合，先创建一个
          if (!hasFeaturedCollection) {
            await db.createCollection('downloadlist');
          }
          // 如果用户已登录，记录到downloads集合
          await db.collection('downloads').add({
            user_id: userId,
            wallpaper_id: wallpaper_id,
            download_time: new Date()
          });
        } else {
          console.log('用户未登录或token无效，仅更新壁纸下载数');
        }
      } catch (userError) {
        console.error('验证用户信息失败:', userError);
        // 即使获取用户信息失败，也继续更新壁纸下载数
      }
    } else {
      console.log('未提供token，仅更新壁纸下载数');
    }
    
    // 更新壁纸下载数（无论用户是否登录都更新）
    await db.collection('wallpapers')
      .doc(wallpaper_id)
      .update({
        data: {
          download_count: _.inc(1),
          downloads: _.inc(1)
        }
      });
    
    return {
      code: 0,
      message: '下载记录成功',
      data: {
        wallpaper_id: wallpaper_id,
        has_user: !!userId
      }
    };
  } catch (error) {
    console.error('记录下载失败:', error);
    // 即使记录失败，也不影响用户下载体验，返回成功
    return {
      code: 0,
      message: '下载记录处理中',
      data: {
        wallpaper_id: wallpaper_id
      }
    };
  }
};